﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dukous.Dao.NHibernate;
using Dukous.Search;
using Dukous.Security.Domain;
using NHibernate;
using NHibernate.Criterion;

namespace Dukous.Security.Dao.NHibernate
{
    public class UserDao : EntityDao<User, long>, IUserDao, ISearchSupport<User>
    {
        #region IUserDao 成员

        public User FindByUserName(string userName)
        {
            IList<User> users = this.HibernateTemplate.ExecuteFind<User>(delegate(ISession session)
            {
                ICriteria criteria = session.CreateCriteria(typeof(User), "u");
                criteria.Add(Expression.Eq("u.UserName", userName));
                return criteria.SetFetchSize(1).List<User>();
            });

            return users.FirstOrDefault();
        }

        #endregion

        #region ISearchSupport<User> 成员

        public IList<User> SelectBySearch(ISearchContext context, out int totalCount)
        {
            int count = 0;
            IList<User> users = this.HibernateTemplate.ExecuteFind<User>(delegate(ISession session)
            {

                ICriteria criteria = session.CreateCriteria(typeof(User), "u");

                count = criteria.SetProjection(Projections.Count("Id").SetDistinct()).UniqueResult<int>();
                if (count == 0)
                {
                    return new List<User>();
                }

                criteria.SetProjection(new IProjection[] { null });
                criteria.SetResultTransformer(CriteriaSpecification.DistinctRootEntity);

                return criteria.SetFirstResult(context.PageSize * (context.PageIndex - 1))
                        .SetMaxResults(context.PageSize)
                        .AddOrder(new global::NHibernate.Criterion.Order("Id", false))
                        .List<User>();
            });

            totalCount = count;

            return users;
        }

        #endregion
    }
}
